import string

from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import DatabaseError
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from bookinfo.models import BookInfo
from django.core.exceptions import ObjectDoesNotExist
import datetime
import pinyin
import time

from leaseList.models import leaseList
from users.models import User


class Book_Info(View):
    # 查询图书信息并展示界面
    def get(self, request, bookid):
        try:
            book = BookInfo.objects.get(id=bookid)
            context = {
                'name': book.name,
                'id': book.id,
                'ISBN': book.ISBN,
                'type': book.type,
                'author': book.author,
                'type_num': book.type_num,
                'pub_hou': book.pub_hou,
                'pub_date': book.pub_date,
                'edition': book.edition,
                'serial_num': book.serial_num,
                'state': book.state,
            }
            return render(request, 'book_info.html', context)
        except ObjectDoesNotExist:
            return HttpResponse('<h1>抱歉，本书库未录入该图书！</h1>')

    def Post(self, request):
        pass


class Search_Book(View):
    def get(self, request):
        # print(request.user)
        p = request.GET.get('p')
        global ID
        # print(p)
        try:
            book = BookInfo.objects.get(name=p)
            ID = book.id
            context = {
                'name': book.name,
                'id': book.id,
                'ISBN': book.ISBN,
                'type': book.type,
                'author': book.author,
                'type_num': book.type_num,
                'pub_hou': book.pub_hou,
                'pub_date': book.pub_date,
                'edition': book.edition,
                'serial_num': book.serial_num,
                'state': book.state,
                'is_staff': request.user.is_staff,
            }
            return render(request, 'book_info.html', context)
        except ObjectDoesNotExist:
            return HttpResponse('<h1>抱歉，本书库未录入该图书！</h1>')

    def post(self, request):
        # 先通过ID找到对应的书籍
        book = BookInfo.objects.get(id=ID)
        print(book.name)
        book.name = request.POST.get('name')
        book.ISBN = request.POST.get("ISBN")
        book.type = request.POST.get("type")
        # book.state = request.POST.get("state")
        book.author = request.POST.get("author")
        book.type_num = request.POST.get("type_num")
        book.pub_hou = request.POST.get("pub_hou")
        book.pub_date = request.POST.get("pub_date")
        book.edition = request.POST.get("edition")
        book.serial_num = request.POST.get("serial_num")
        book.save()
        return render(request, 'search_book.html')


class delete_book(View):
    def get(self, request):
        book = BookInfo.objects.get(id=ID)
        print(book.is_deleted)
        print(book.is_deleted)
        book.is_deleted = True
        book.save()
        print(book.is_deleted)
        return HttpResponse("<h1>删除成功</h1>")


class BorrowBook(View):
    # 此功能有两个实现 1.实现图书状态的该表 2. 实现图书借阅信息的生成
    def get(self, request):
        book = BookInfo.objects.get(id=ID)
        print(book)
        return HttpResponse("图书状态改变了")

    def post(self, request):
        book = BookInfo.objects.get(id=ID)
        # 借书人首字母
        username = request.user.username,
        user_name = username[0]
        print(user_name)
        # 按照用户名把borrwo_number 查出来
        user = User.objects.get(username=user_name)
        print(user)
        print(f'借了{user.borrow_number}本书')
        user_name = pinyin.get_initial(user_name, delimiter="").upper()
        # 书名首字母
        book_name = pinyin.get_initial(book.name, delimiter="").upper()
        # 时间 年份后两位 + 月份 + 日期
        borrow_time = time.strftime("%Y%m%d")
        borrow_time = borrow_time[2:]
        # print(f"时间的类型是：{type(borrow_time)}{borrow_time}")
        # 借阅编号：学生首字母 + 书名首字母 + 时间
        # 图书编号
        TUBH = user_name + book_name + borrow_time
        # print(TUBH)
        # 借阅者姓名
        JUZXM = username[0]
        # print(JUZXM)
        # 学号
        JUZXH = request.user.mobile
        # print(JUZXH)
        # 借阅图书书名
        JUTSSM = book.name
        # print(JUTSSM)
        # 借出时间
        JCSJ = datetime.datetime.now()
        JCSJ_STR = str(JCSJ)
        # print(f"转换之后借出时间为{str(JCSJ)}类型是{type(str(JCSJ))}")
        # print(f"借出时间为{JCSJ}类型是{type(JCSJ)}")
        # 最迟还书日期
        delta = datetime.timedelta(days=90)
        ZCHSSJ = delta + JCSJ
        ZCHSSJ_STR = str(ZCHSSJ)
        # print(f"最迟还书时间{ZCHSSJ}类型是：{type(ZCHSSJ)}")
        try:
            leaseList.objects.create(
                borrow_id=TUBH, name=JUZXM,
                name_id=JUZXH, book_name=JUTSSM,
                book_id=ID, borrow_date=JCSJ,
                return_date=ZCHSSJ,
            )
            user.number += 1
            user.save()
        except DatabaseError:
            return HttpResponse('<h1>借阅失败</h1>')

        return HttpResponse("<h1>借阅信息已生成</h1>")
